#!/usr/bin/python
# -*- coding: utf-8 -*-
# @version        : 1.0
# @Create Time    : 2024/9/6 11:11
# @File           : __init__
# @IDE            : PyCharm
# @desc           : 描述

from sqlalchemy.ext.asyncio import AsyncSession
from core.crud import DalBase
from . import models, schemas
from apps.check.feature.crud import ASRFeatureDal
from apps.check.param.crud import ParamDal
from core.exception import CustomException
from apps.base.external.crud import ExternDal


class QARFemaleDal(DalBase):

    def __init__(self, db: AsyncSession):
        super(QARFemaleDal, self).__init__()
        self.db = db
        self.model = models.DCQARFemale
        self.schema = schemas.QARFemaleSimpleOut

    async def create_data(self, data: schemas.QARFemaleIn):
        unique = await self.get_data(part_no=data.part_no, v_return_none=True)
        if unique: raise CustomException("该件号母本已存在，不可新建")
        
        features = await ASRFeatureDal(self.db).get_datas(part_no=data.part_no, v_return_objs=True)
        data.asr_features = [schemas.QARFemaleFeature.model_validate(i) for i in features]
    
        params = await ParamDal(self.db).get_datas(limit=0, is_active=True, v_return_objs=True, 
                                                   param_type=('in', ['实验要求', '限制要求', '检验项目']))
        data.contents = []
        for param in params:
            data.contents.append(schemas.QARFemaleContent(
                content_type=param.param_type,
                project= f'({param.param_value}) {param.param_name}' if param.param_type == '检验项目' else param.param_name,
                detail=param.param_detail.split(";") if param.param_detail else [],
                detail_value=['' for _ in param.param_detail.split(";")] if param.param_detail else []
            ))
        return await super().create_data(data=data, v_schema=schemas.QARFemaleOut)
    
    async def put_data(self, data_id, data:schemas.QARFemaleIn):
        obj = await self.get_data(data_id=data_id)
        if obj.status == "启用":
            raise CustomException("已启用母本不允许编辑，请去升版")
        return await super().put_data(data_id=data_id, data=data, v_schema=schemas.QARFemaleOut)
    

    async def get_material(self, **params):
        async for resp in ExternDal().get_material(**params):
            return resp["list"], int(resp["total_count"])
